<template>
  <view class="register-container">
    <view class="register-header">
      <view class="register-logo">
        <image src="/static/logo.png" mode="aspectFit"></image>
        <text class="logo-text">MoeConnect</text>
      </view>
      <text class="register-title">创建账户</text>
      <text class="register-subtitle">加入我们，开启精彩旅程</text>
    </view>
    
    <view class="register-card">
      <view class="form-content">
        <view class="form-group">
          <label for="name" class="form-label">昵称</label>
          <view class="input-wrapper">
            <i class="fas fa-user input-icon"></i>
            <input id="name" v-model="form.name" type="text" class="form-input" placeholder="请输入昵称" />
          </view>
          <view v-if="errors.name" class="error-message">{{ errors.name }}</view>
        </view>

        <view class="form-group">
          <label for="register-email" class="form-label">邮箱</label>
          <view class="input-wrapper">
            <i class="fas fa-envelope input-icon"></i>
            <input id="register-email" v-model="form.email" type="text" class="form-input" placeholder="请输入邮箱" />
          </view>
          <view v-if="errors.email" class="error-message">{{ errors.email }}</view>
        </view>

        <view class="form-group">
          <label for="register-password" class="form-label">密码</label>
          <view class="input-wrapper">
            <i class="fas fa-lock input-icon"></i>
            <input 
              id="register-password"
              v-model="form.password" 
              :type="showPassword ? 'text' : 'password'" 
              class="form-input" 
              placeholder="请输入密码" 
            />
            <i
              :class="showPassword ? 'fas fa-eye' : 'fas fa-eye-slash'"
              class="toggle-password"
              @click="showPassword = !showPassword"
            ></i>
          </view>
          <view v-if="errors.password" class="error-message">{{ errors.password }}</view>
        </view>

        <view class="form-group">
          <label for="confirm-password" class="form-label">确认密码</label>
          <view class="input-wrapper">
            <i class="fas fa-lock input-icon"></i>
            <input 
              id="confirm-password"
              v-model="form.confirmPassword" 
              :type="showConfirmPassword ? 'text' : 'password'" 
              class="form-input" 
              placeholder="请再次输入密码" 
            />
            <i
              :class="showConfirmPassword ? 'fas fa-eye' : 'fas fa-eye-slash'"
              class="toggle-password"
              @click="showConfirmPassword = !showConfirmPassword"
            ></i>
          </view>
          <view v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</view>
        </view>

        <view class="form-group agree-terms">
          <label class="checkbox-container">
            <checkbox 
              :checked="form.agreeTerms" 
              @change="form.agreeTerms = !form.agreeTerms" 
              class="form-checkbox"
              color="#7B68EE"
            />
            <text class="checkbox-label">我已阅读并同意</text>
            <text class="link-text" @click="handleViewTerms">《服务条款》</text>
            <text class="and-text">和</text>
            <text class="link-text" @click="handleViewPrivacy">《隐私政策》</text>
          </label>
          <view v-if="errors.agreeTerms" class="error-message">{{ errors.agreeTerms }}</view>
        </view>

        <button type="button" class="btn-primary auth-btn" :disabled="isLoading" @click="handleRegister">
          <template v-if="isLoading">
            <i class="fas fa-spinner fa-spin loading-icon"></i>
            <text>注册中...</text>
          </template>
          <template v-else>注册</template>
        </button>
      </view>
    </view>
    
    <view class="login-link">
      <text class="login-text">已有账户？</text>
      <text class="login-btn" @click="goToLogin">立即登录</text>
    </view>
  </view>
</template>

<script>
import { ref, reactive } from 'vue'
import { register } from '@/api/user.js'
import { validateRegisterForm } from '@/utils/auth'
import { handleApiError } from '@/utils/error-handler'

export default {
  name: 'RegisterPage',
  data() {
    return {
      form: {
        name: '',
        email: '',
        password: '',
        confirmPassword: '',
        agreeTerms: false
      },
      errors: {},
      isLoading: false,
      showPassword: false,
      showConfirmPassword: false,
      isNavigating: false // 新增导航状态
    }
  },
  methods: {
    async handleRegister() {
      // 用户点击注册按钮
      
      // 内置表单验证逻辑
      const errors = {}
      
      // 验证昵称
      if (!this.form.name || this.form.name.trim() === '') {
        errors.name = '请输入昵称'
      } else if (this.form.name.length < 2) {
        errors.name = '昵称长度至少为2位'
      } else if (this.form.name.length > 20) {
        errors.name = '昵称长度不能超过20位'
      }
      
      // 验证邮箱
      if (!this.form.email) {
        errors.email = '请输入邮箱'
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.form.email)) {
        errors.email = '请输入有效的邮箱地址'
      }
      
      // 验证密码
      if (!this.form.password) {
        errors.password = '请输入密码'
      } else if (this.form.password.length < 8) {
        errors.password = '密码长度至少为8位'
      } else if (this.form.password.length > 50) {
        errors.password = '密码长度不能超过50位'
      }
      
      // 验证确认密码
      if (!this.form.confirmPassword) {
        errors.confirmPassword = '请确认密码'
      } else if (this.form.confirmPassword !== this.form.password) {
        errors.confirmPassword = '两次输入的密码不一致'
      }
      
      // 暂时隐藏服务条款校验，保留UI但不强制要求
      // if (!this.form.agreeTerms) {
      //   errors.agreeTerms = '请阅读并同意服务条款和隐私政策'
      // }
      
      this.errors = errors
    
      if (Object.keys(errors).length > 0) {
        return
      }
    
      try {
        this.isLoading = true
        const response = await register(this.form)
        // 注册成功
        
        uni.showToast({ title: '注册成功', icon: 'success' })
        
        // 注册成功后跳转到登录页面，并传递注册的邮箱
        setTimeout(() => {
          uni.redirectTo({
            url: `/pages/login/login?email=${this.form.email}`
          })
        }, 1500)
      } catch (error) {
        // 注册失败
        uni.showToast({ title: error.message || '注册失败', icon: 'none' })
      } finally {
        this.isLoading = false
      }
    },
    handleViewTerms() {
      // 查看服务条款
      uni.navigateTo({
        url: '/pages/terms/terms'
      })
    },
    
    handleViewPrivacy() {
      // 查看隐私政策
      uni.navigateTo({
        url: '/pages/privacy/privacy'
      })
    },
    
    goToLogin() {
        // 防止重复点击
        if (this.isNavigating) {
            return;
        }
        
        this.isNavigating = true;
        
        // 添加点击反馈
        uni.vibrateShort();
        
        // 使用延迟跳转，确保动画流畅
        setTimeout(() => {
            uni.navigateTo({
                url: '/pages/login/login',
                animationType: 'slide-in-left',
                animationDuration: 300,
                success: () => {
                    console.log('跳转到登录页面成功');
                },
                fail: (err) => {
                    console.error('跳转到登录页面失败:', err);
                    this.isNavigating = false;
                },
                complete: () => {
                    // 重置导航状态
                    setTimeout(() => {
                        this.isNavigating = false;
                    }, 500);
                }
            });
        }, 100);
    }
  }
}
</script>

<style>
/* 引入外部CSS文件 */
@import url('./register.css');
</style>

<style scoped>
/* 此处保留组件特有样式 */
.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
}

/* 同意条款特有样式 */
.agree-terms {
  margin-top: 20px;
}

.checkbox-container {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.form-checkbox {
  transform: scale(1.2);
  margin-right: 8px;
}

.checkbox-label {
  flex-shrink: 0;
}

.link-text {
  text-decoration: underline;
  cursor: pointer;
}

.and-text {
  margin: 0 5px;
}
</style>